import 'package:ladder_cash/Global.dart';
import 'package:ladder_cash/app/com/service/burial_point_service.dart';
import 'package:ladder_cash/app/com/service/reported_data_service.dart';
import 'package:ladder_cash/app/com/util/permission_utils.dart';
import 'package:ladder_cash/app/com/view/my_date_picker.dart';
import 'package:ladder_cash/app/key_mix.dart';
import 'package:ladder_cash/app/page/component/decoration_bg.dart';
import 'package:ladder_cash/gen/assets.gen.dart';
import 'package:ladder_cash/generated/assets.dart' as myAssets;
import 'package:ladder_cash/generated/l10n.dart';
import 'package:ladder_cash/value/app_colors.dart';
import 'package:ladder_cash/value/app_const.dart';
import 'package:ladder_cash/value/app_lstyle.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_contact_picker/flutter_native_contact_picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/view/loading_view.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:liuxlcommon/view/my_box.dart';
import 'package:liuxlcommon/view/my_style.dart';

import '../../../library/src/logger.dart';
import '../component/common.dart';
import 'authentication_logic.dart';

///联系人信息
class EmergencyContactPage extends StatefulWidget {
  EmergencyContactPage({super.key});

  @override
  _AuthenticationPageState createState() => _AuthenticationPageState();
}

class _AuthenticationPageState extends State<EmergencyContactPage> {
  final logic = Get.put(AuthenticationLogic());

  @override
  void initState() {
    super.initState();
    Logger.d("EmergencyContactPage");
    BurialPointService.start(BPoint.contact);
  }

  @override
  Widget build(BuildContext context) {
    return LoadingView(
        isPullDown: true,
        future: () => logic.getContactInfo(),
        datas: logic.authenticationInfo,
        onSuccess: () {
          if (logic.authenticationInfo != null) logic.update();
        },
        body: () => Column(
              children: [
                getTitleTop(),
                Expanded(
                    child: Container(
                  width: Global.width,
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  decoration: BoxDecoration(
                    borderRadius: getTopRadius(),
                    color: Colors.white,
                  ),
                  child: list,
                )),
                confirmBtn
              ],
            ));
  }

  get confirmBtn => LColumn(lStyle: LStyle(css: '''
      width: 375px;
    background: #FFFFFF;
  height: 112px; 
    '''), children: [
        LSizeBoxHeight(16.w),
        Container(
          height: 53.w,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: commonBtn(S.current.next, callback: () {
            logic.saveContactInfo();
          }),
        ),
        LSizeBoxHeight(42.w)
      ]);

  Widget get list => <Widget>[
        for (var i = 0;
            i < logic.authenticationInfo!['emergent'.hx].length;
            i++)
          itemView(logic.authenticationInfo!['emergent'.hx][i], i),
        LSizeBoxHeight(20.w)
      ].setColumnSlid(LStyle(
        css: '''  margin-top:16px;
          width:343px;''',
        crossAxisAlignment: CrossAxisAlignment.start,
      ));

  itemView(item, index) {
    return LColumn.eazy([
      LRow.eazy([
        8.lsw,
        LText.easy(item['title'.hx], 15.sp, fw7, AppColors.textColor).flex(1)
      ]).size(double.infinity, 44.w),
      // LContainer().bgColor(AppColors.primaryColor).size(343.w, 1.w),
      //  LSizeH(26.w),
      Card(
        child: LColumn.eazy([
          itemSingleSelection(item),
          LSizeH(14.w),
          itemContact(item),
          LSizeH(14.w),
        ]).paddingAll(15.w).bgColor(Colors.white),
      )
    ]).margin(bottom: 24.w);
  }

  get itemTitleSty => LStyle(css: '''font-weight: 500;
font-size: 16px;
color: #333333;''', width: double.infinity, alignment: Alignment.centerLeft);

  get itemNameSty =>
      LStyle(alignment: Alignment.centerLeft, css: '''height: 22px;
font-size: 14px;
margin-bottom:7px;
font-weight: 400;''');

  get pointView => LContainer(
      lStyle: LStyle(
          width: 8.w,
          height: 8.w,
          backgroundColor: const Color(0xFF22C663),
          radius: 4.w));

  itemSingleSelection(item) {
    List<String> lists = [];
    Map keyMap = {};
    for (dynamic d in item['note'.hx]) {
      var strss = d['name'.hx];
      lists.add(strss);
      if (d['type'.hx] == item['relation'.hx]) {
        item['handkerchief'] = d['name'.hx];
      }
      keyMap[d['name'.hx]] = d['type'.hx];
    }
    bool empty = (item?['handkerchief'] ?? "").toString().isEmpty;
    return LStack([
      LColumn.eazy([
        LText(item['relation_text'.hx], lStyle: itemNameSty),
        LRow.eazy([
          LText(!empty ? item['handkerchief'] : item['relation_reminder'.hx],
              lStyle: inputSty
                ..color = !empty ? Colors.black : AppColors.textSecondColor),
          const Icon(
            color: Color(0xff666666),
            Icons.arrow_forward_ios_rounded,
            size: 20.0, // 可根据需要调整图标大小
          )
        ]).css(inputBoxCss)
      ])
    ]).onTapL(() => {
          MyDatePicker.showSinglePicker(context,
              data: lists,
              title: "Relationship",
              selectData: item['handkerchief'] ?? "", onConfirm: (txt, i) {
            item['handkerchief'] = txt;
            item['relation'.hx] = keyMap[txt];
            logic.update();
          })
        });
  }

  itemContact(item) {
    String name = item['name'.hx];
    String mobile = item['mobile'.hx];
    bool empty = (item?['mobile'.hx] ?? "").toString().isEmpty;
    return LStack([
      LColumn.eazy([
        LText(item['mobile_text'.hx], lStyle: itemNameSty),
        LRow.eazy([
          LText(!empty ? '$name $mobile' : item['mobile_reminder'.hx],
              lStyle: inputSty
                ..color =
                    !empty ? AppColors.textColor : AppColors.textSecondColor),
          LImage.easy(Assets.img.phone.path, 12.w, 14.w)
        ])
          ..css(inputBoxCss)
      ])
    ]).onTapL(() async {
      PermissionUtils.checkContactPermission(() async {
        ReportedDataService().reportContact();
        // Contact? contact = await FlutterContactPicker().selectContact();
        Contact? contact = await FlutterContactPicker().selectContact();
        if (contact != null) {
          item['name'.hx] = contact.fullName;
          item['mobile'.hx] = contact.phoneNumbers![0];
          logic.update();
        }
      });
    });
  }
}
